//
//  MemberViewController.m
//  Hxcsfw
//
//  Created by 企友软mac on 2018/3/2.
//  Copyright © 2018年 企友软mac. All rights reserved.
//

#import "MemberViewController.h"
#import "MemberCell.h"
#import "IAPHelper.h"
#import "IAPProduct.h"
#import "MemberModel.h"
#import "UIImageView+WebCache.h"
#import "LoginViewController.h"

@interface MemberViewController ()<UITableViewDelegate, UITableViewDataSource,MemberCellDelegate> {
    IAPProduct *product;
    NSInteger pageMark;
    NSString *strImg;
    UIView *viewContent;
    UIView *bgMebemView;
}

@property (nonatomic, strong)UITableView *tableView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *highCon;
@property (weak, nonatomic) IBOutlet UIView *lineViewL;
@property (weak, nonatomic) IBOutlet UIView *lineViewM;
@property (weak, nonatomic) IBOutlet UIView *lineViewR;

@property (weak, nonatomic) IBOutlet UIButton *btnL;
@property (weak, nonatomic) IBOutlet UIButton *btnM;
@property (weak, nonatomic) IBOutlet UIButton *btnR;

@property (strong, nonatomic) NSArray *arrCs;
@property (strong, nonatomic) NSArray *arrYs;
@property (strong, nonatomic) NSArray *arrStudy;
@property (strong, nonatomic) NSMutableArray *arrData;

@property (nonatomic, strong) IAPHelper  *m_iapHelper;
@property (nonatomic, strong) NSMutableArray *m_productArray;

@end

@implementation MemberViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(memberBuyNotify) name:MEMBER_BNY_NOTIFY object:nil];

    if (XIPHONE) {
        _highCon.constant = 88;
    } else {
        _highCon.constant = 64;
    }
    _arrData = [NSMutableArray array];
    [self reportObtainMemberInfo:@"1"];
    strImg = @"diamond_logo.png";
    pageMark = 0;
    _arrCs = @[@{@"strImg":@"gold_logo.png",@"strTit":@"金卡",@"strPrice":@"价格：￥5898/年"},@{@"strImg":@"gold_logo.png",@"strTit":@"金卡A1",@"strPrice":@"价格：￥5898/年"},
               @{@"strImg":@"sviler_logo.png",@"strTit":@"银卡A",@"strPrice":@"价格：￥2998/年"},@{@"strImg":@"sviler_logo.png",@"strTit":@"银卡A1",@"strPrice":@"价格：￥2998/年"},
               @{@"strImg":@"diamond_logo.png",@"strTit":@"普A1",@"strPrice":@"价格：￥2298/年"},@{@"strImg":@"diamond_logo.png",@"strTit":@"普A2",@"strPrice":@"价格：￥2298/年"},
               @{@"strImg":@"diamond_logo.png",@"strTit":@"普B1",@"strPrice":@"价格：￥1998/年"},@{@"strImg":@"diamond_logo.png",@"strTit":@"普B2",@"strPrice":@"价格：￥1998/年"},
               @{@"strImg":@"diamond_logo.png",@"strTit":@"普C1",@"strPrice":@"价格：￥1148/年"},@{@"strImg":@"diamond_logo.png",@"strTit":@"普C2",@"strPrice":@"价格：￥798/年"}];
    _arrYs = @[@{@"strImg":@"yst_logo.png",@"strTit":@"产品A",@"strPrice":@"价格：￥4498/年"},@{@"strImg":@"yst_logo.png",@"strTit":@"产品B",@"strPrice":@"价格：￥1998/年"}];
    _arrStudy = @[@{@"strImg":@"study_logo.png",@"strTit":@"学习卡A",@"strPrice":@"价格：￥2298/年"},@{@"strImg":@"study_logo.png",@"strTit":@"学习卡B",@"strPrice":@"价格：￥1448/年"},@{@"strImg":@"study_logo.png",@"strTit":@"学习卡C",@"strPrice":@"价格：￥798/年"}];

//    _arrData = _arrCs;
    [self.view addSubview:self.tableView];
    [_btnL setTitleColor:[UIColor colorWithRed:0.22 green:0.59 blue:0.89 alpha:1] forState:UIControlStateNormal];
    [_btnM setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [_btnR setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HYJFNOTICE) name:@"HYJF" object:nil];

    [self loadData];
}

- (void)memberBuyNotify {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)HYJFNOTICE {
    [self reportSetupMemberInfo];
}

- (UITableView *)tableView {

    if (_tableView == nil) {

        if (XIPHONE) {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 150, WSCREENH_WIDTH, WSCREENH_HEIGHT - 150) style:UITableViewStylePlain];

        } else {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 124, WSCREENH_WIDTH, WSCREENH_HEIGHT - 124) style:UITableViewStylePlain];

        }
        _tableView.delegate = self;
        _tableView.dataSource = self;
        self.tableView.estimatedRowHeight =0;
        self.tableView.estimatedSectionHeaderHeight =0;
        self.tableView.estimatedSectionFooterHeight =0;
        _tableView.showsVerticalScrollIndicator = YES;
        _tableView.bounces = YES;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _arrData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *identCell = @"NetworkPayCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identCell];
    if (cell == nil) {
        MemberCell *memberCell = [[[NSBundle mainBundle] loadNibNamed:@"MemberCell" owner:self options:nil] lastObject];
        memberCell.btnImmediately.tag = [[_arrData[indexPath.row] HYDM] integerValue];

        [memberCell.imgCell sd_setImageWithURL:[NSURL URLWithString:[_arrData[indexPath.row] IMG]] placeholderImage:[UIImage imageNamed:strImg]];
        memberCell.lbTit.text = [_arrData[indexPath.row] HYNAME];
        memberCell.lbPrice.text = [NSString stringWithFormat:@"价格：￥%@/年",[_arrData[indexPath.row] PRICE]];
        memberCell.delegate = self;
        cell = memberCell;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }
    return cell;
}

- (IBAction)seletBtnClick:(UIButton *)sender {
    if (sender.tag == 0) {
        _lineViewL.hidden = NO;
        _lineViewM.hidden = YES;
        _lineViewR.hidden = YES;
        [_btnL setTitleColor:[UIColor colorWithRed:0.22 green:0.59 blue:0.89 alpha:1] forState:UIControlStateNormal];
        [_btnM setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_btnR setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];

        [self reportObtainMemberInfo:@"1"];
//        _arrData = _arrCs;
        pageMark = 0;
        strImg = @"diamond_logo.png";
    } else if (sender.tag == 1) {
        _lineViewL.hidden = YES;
        _lineViewM.hidden = NO;
        _lineViewR.hidden = YES;
        [_btnL setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_btnM setTitleColor:[UIColor colorWithRed:0.22 green:0.59 blue:0.89 alpha:1] forState:UIControlStateNormal];
        [_btnR setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];

        [self reportObtainMemberInfo:@"2"];

//        _arrData = _arrYs;
        pageMark = 1;
        strImg = @"yst_logo.png";

    } else if (sender.tag == 2) {
        _lineViewL.hidden = YES;
        _lineViewM.hidden = YES;
        _lineViewR.hidden = NO;
        [_btnL setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_btnM setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_btnR setTitleColor:[UIColor colorWithRed:0.22 green:0.59 blue:0.89 alpha:1] forState:UIControlStateNormal];

        [self reportObtainMemberInfo:@"3"];

//        _arrData = _arrStudy;
        pageMark = 2;
        strImg = @"study_logo.png";
    }
    [self.tableView reloadData];
}

- (void)delegatBtnClick:(UIButton *)button {

#if TARGET_IPHONE_SIMULATOR
    [WShareUtil showAlert:@"温馨提示" message:@"请用真机购买"];
    WLog(@"run on simulator");
    return;
#define SIMULATOR_TEST
#else
    //不定义SIMULATOR_TEST这个宏
    switch (button.tag) {
        case 2880:
            product = self.m_productArray[0];
            break;
        case 3540:
            product = self.m_productArray[1];
            break;
        case 400:
            product = self.m_productArray[2];
            break;
        case 1220:
            product = self.m_productArray[3];
            break;
        case 803:
            product = self.m_productArray[4];
            break;
        case 3520:
            product = self.m_productArray[5];
            break;
        case 1123:
            product = self.m_productArray[6];
            break;
        case 3541:
            product = self.m_productArray[7];
            break;
        case 1125:
            product = self.m_productArray[8];
            break;
        case 1126:
            product = self.m_productArray[9];
            break;
        case 3480:
            product = self.m_productArray[10];
            break;
        case 3481:
            product = self.m_productArray[11];
            break;
        case 3500:
            product = self.m_productArray[12];
            break;
        case 3501:
            product = self.m_productArray[13];
            break;
        case 3502:
            product = self.m_productArray[14];
            break;
        default:
            break;
    }
    [WShareUtil sharedData].memberId = [NSString stringWithFormat:@"%ld",button.tag];

    [WShareUtil sharedData].isMember = YES;

    if ([WShareUtil sharedData].dicSession) {

        [self reportSetupMemberInfo];
//        [WShareUtil sharedData].isShowWait = YES;
//        [WShareUtil showWait:YES frame:CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT)];
//
//        [IAPHelper sharedData];
//        self.m_iapHelper = [IAPHelper new];
//        self.m_iapHelper.m_buyType = product.m_buyType;
//        [self.m_iapHelper requestProductData];
    } else {

        [self openMemberSheet];
    }

#endif
}


#pragma mark 创建订单信息
- (void)reportSetupMemberInfo {

    NSDictionary *parametersDict;
    NSString *username;
    NSString *nologinuser;

    WLog(@"%@",[WShareUtil sharedData].memberId);
    NSString *dto = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:@{@"cat":@"2",@"productId":[WShareUtil sharedData].memberId}]];

    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"username":username,@"apptype":@"ios",@"revert":@"create",@"dto":dto}};
    } else {
        nologinuser = [WShareUtil getUUID];
        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"nologinuser":nologinuser,@"apptype":@"ios",@"revert":@"create",@"dto":dto}};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];

    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr isEqualToString:@"true"]) {
            [WShareUtil sharedData].dicMemberOrder = returnDic;

            [WShareUtil sharedData].isShowWait = YES;
            [WShareUtil showWait:YES frame:CGRectMake(0, 32, WSCREENH_WIDTH, WSCREENH_HEIGHT)];

            [IAPHelper sharedData];
            self.m_iapHelper = [IAPHelper new];
            self.m_iapHelper.m_buyType = product.m_buyType;
            [self.m_iapHelper requestProductData];
        } else {
            [WShareUtil showAlert:@"温馨提示" message:returnDic[@"errorInfo"]];
        }
    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

- (void)loadData {

    IAPProduct *product1 = [IAPProduct new];
    product1.m_buyType = ID_GoldA;

    IAPProduct *product2 = [IAPProduct new];
    product2.m_buyType = ID_GoldA1;

    IAPProduct *product3 = [IAPProduct new];
    product3.m_buyType = ID_SilverA;

    IAPProduct *product4 = [IAPProduct new];
    product4.m_buyType = ID_SilverA1;

    IAPProduct *product5 = [IAPProduct new];
    product5.m_buyType = ID_CommonA1;

    IAPProduct *product6 = [IAPProduct new];
    product6.m_buyType = ID_CommonA2;

    IAPProduct *product7 = [IAPProduct new];
    product7.m_buyType = ID_CommonB1;

    IAPProduct *product8 = [IAPProduct new];
    product8.m_buyType = ID_CommonB2;

    IAPProduct *product9 = [IAPProduct new];
    product9.m_buyType = ID_CommonC1;

    IAPProduct *product10 = [IAPProduct new];
    product10.m_buyType = ID_CommonC2;

    IAPProduct *product11 = [IAPProduct new];
    product11.m_buyType = ID_ProductA;
    IAPProduct *product12 = [IAPProduct new];
    product12.m_buyType = ID_ProductB;

    IAPProduct *product13 = [IAPProduct new];
    product13.m_buyType = ID_StudyA;
    IAPProduct *product14 = [IAPProduct new];
    product14.m_buyType = ID_StudyB;
    IAPProduct *product15 = [IAPProduct new];
    product15.m_buyType = ID_StudyC;

    self.m_productArray = [NSMutableArray arrayWithObjects:product1,product2,product3,product4,product5,product6,product7,product8,product9,product10,product11,product12,product13,product14,product15, nil];
}

// 获取会员信息
- (void)reportObtainMemberInfo:(NSString *)type {

    NSDictionary *parametersDict;
    NSString *username;
    NSString *nologinuser;

    NSString *dto = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:@{@"page":@"1",@"limit":@"20",@"service":@"order",@"type":type}]];

    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"apptype":@"ios",@"revert":@"memberTypeList",@"username":username,@"dto":dto}};
    } else {
        nologinuser = [WShareUtil getUUID];
        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"nologinuser":nologinuser,@"apptype":@"ios",@"revert":@"memberTypeList",@"dto":dto}};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];

    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
    
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        [_arrData removeAllObjects];
        for (NSDictionary *dic in returnDic[@"data"]) {
            MemberModel *memberModel = [MemberModel mj_objectWithKeyValues:dic];
            [_arrData addObject:memberModel];
        }

        [self.tableView reloadData];
        if (![successStr isEqualToString:@"true"]) {
//            [WShareUtil showAlert:@"温馨提示" message:returnDic[@"errorInfo"]];
        }
    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

- (void)openMemberSheet {

    bgMebemView = [[UIView alloc] initWithFrame:self.view.bounds];
    bgMebemView.backgroundColor = WRGBAColor(0, 0, 0, 0.5);
    [self.view addSubview:bgMebemView];

    viewContent = [[UIView alloc] initWithFrame:CGRectMake((WSCREENH_WIDTH - 280) * 0.5, (WSCREENH_HEIGHT - 240) * 0.5, 280, 235)];
    viewContent.backgroundColor = WRGBColor(255, 255, 255);
    viewContent.layer.cornerRadius = 10;

    UILabel *lbTit = [[UILabel alloc] initWithFrame:CGRectMake(0, 15, 280, 20)];
    lbTit.backgroundColor = [UIColor whiteColor];
    lbTit.text = @"开通会员";
    lbTit.font = [UIFont systemFontOfSize:16];
    lbTit.textAlignment = NSTextAlignmentCenter;
    [viewContent addSubview:lbTit];

    UILabel *lbSubheading1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 45, 280, 20)];
    lbSubheading1.backgroundColor = [UIColor whiteColor];
    lbSubheading1.font = [UIFont systemFontOfSize:14];
    lbSubheading1.text = @"登录掌税通购买:可跨平台享受会员权益";
    lbSubheading1.textAlignment = NSTextAlignmentCenter;
    [viewContent addSubview:lbSubheading1];

    UILabel *lbSubheading2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 70, 280, 20)];
    lbSubheading2.backgroundColor = [UIColor whiteColor];
    lbSubheading2.font = [UIFont systemFontOfSize:14];
    lbSubheading2.text = @"游客身份购买:仅限本设备开通会员";
    lbSubheading2.textAlignment = NSTextAlignmentCenter;
    [viewContent addSubview:lbSubheading2];

    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 99, 280, 1)];
    lineView.backgroundColor = WRGBColor(243, 243, 243);
    [viewContent addSubview:lineView];

    UIButton *btnMember = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 280, 44)];
    [btnMember.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [btnMember setTitle:@"登录掌税通购买" forState:UIControlStateNormal];
    [btnMember setTitleColor:WRGBColor(46, 141, 238) forState:UIControlStateNormal];
    btnMember.tag = 100;
    [btnMember addTarget:self action:@selector(btnOpenClick:) forControlEvents:UIControlEventTouchUpInside];
    [viewContent addSubview:btnMember];

    UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 143, 280, 1)];
    lineView1.backgroundColor = WRGBColor(243, 243, 243);
    [viewContent addSubview:lineView1];

    UIButton *btnTourist = [[UIButton alloc] initWithFrame:CGRectMake(0, 144, 280, 44)];
    [btnTourist.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [btnTourist setTitle:@"游客身份购买" forState:UIControlStateNormal];
    [btnTourist setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    btnTourist.tag = 110;
    [btnTourist addTarget:self action:@selector(btnOpenClick:) forControlEvents:UIControlEventTouchUpInside];
    [viewContent addSubview:btnTourist];

    UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 187, 280, 1)];
    lineView2.backgroundColor = WRGBColor(243, 243, 243);
    [viewContent addSubview:lineView2];

    UIButton *btnLogin = [[UIButton alloc] initWithFrame:CGRectMake(0, 188, 280, 44)];
    [btnLogin.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [btnLogin setTitle:@"取消" forState:UIControlStateNormal];
    [btnLogin addTarget:self action:@selector(btnOpenClick:) forControlEvents:UIControlEventTouchUpInside];
    btnLogin.tag = 120;
    [btnLogin setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [viewContent addSubview:btnLogin];

    [self.view addSubview:viewContent];

}

- (void)btnOpenClick:(UIButton *)btn {

    if (btn.tag == 100) {

        [WShareUtil sharedData].Who = @"HYJF";
        LoginViewController *loginVc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVc animated:YES];

    } else if (btn.tag == 110) {
        [self reportSetupMemberInfo];
    } else {

    }

    [bgMebemView removeFromSuperview];
    [viewContent removeFromSuperview];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [WShareUtil showWait:NO frame:CGRectZero];
}

- (void)dealloc {
    //移除所有通知监控
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
